package com.wannengbang.storemobile.a_main;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.maps.MapsInitializer;
import com.amap.api.services.core.ServiceSettings;
import com.wannengbang.storemobile.MyApplication;
import com.wannengbang.storemobile.R;
import com.wannengbang.storemobile.base.BaseActivity;
import com.wannengbang.storemobile.base.DataCallBack;
import com.wannengbang.storemobile.bean.BaseResponseBean;
import com.wannengbang.storemobile.bean.VersionBean;
import com.wannengbang.storemobile.event.AddressEvent;
import com.wannengbang.storemobile.event.ReLoginEvent;
import com.wannengbang.storemobile.homepage.HomePageFragment;
import com.wannengbang.storemobile.homepage.ScanCodeActivity;
import com.wannengbang.storemobile.homepage.model.HomePageModelImpl;
import com.wannengbang.storemobile.login.LoginActivity;
import com.wannengbang.storemobile.mine.MineFragment;
import com.wannengbang.storemobile.mine.model.MineModelImpl;
import com.wannengbang.storemobile.utils.AMapManager;
import com.wannengbang.storemobile.utils.NumberFormatUtils;
import com.wannengbang.storemobile.utils.PermissionsManager;
import com.wannengbang.storemobile.utils.SPManager;
import com.wannengbang.storemobile.utils.ToastUtil;
import com.wannengbang.storemobile.utils.VersionUtil;
import com.wannengbang.storemobile.widget.CommonNoTitleDialog;
import com.wannengbang.storemobile.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends BaseActivity {


    @BindView(R.id.fragment_container)
    FrameLayout fragmentContainer;
    @BindView(R.id.iv_home_icon)
    ImageView ivHomeIcon;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.ll_home_page)
    LinearLayout llHomePage;
    @BindView(R.id.iv_mine_icon)
    ImageView ivMineIcon;
    @BindView(R.id.tv_mine)
    TextView tvMine;
    @BindView(R.id.ll_mine)
    LinearLayout llMine;
    @BindView(R.id.foot_id)
    RelativeLayout footId;
    @BindView(R.id.main_rootView)
    RelativeLayout mainRootView;

    public static final String fragmentTag_home = "home";
    public static final String fragmentTag_mine = "mine";
    public static final String MAIN_TAB = "main_tab";

    private HomePageFragment homePageFragment;
    private MineFragment mineFragment;


    private PermissionsManager permissionsManager;
    private String[] permissions;
    private CommonNoTitleDialog.Builder dialogBuild;
    private static final String TAG = "Main";
    private Handler handler = new Handler();
    private AMapManager aMapManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        registerEventBus();
        initView();
        //隐私政策合规
        ServiceSettings.updatePrivacyShow(this,true,true);
        ServiceSettings.updatePrivacyAgree(this,true);
        getPermissions();

        requestClientVersion();

    }


    private void initView() {
        handlerFragmentShowHide(fragmentTag_home);
    }

    private void requestClientVersion() {
        new HomePageModelImpl().requestClientVersion(new DataCallBack<VersionBean>() {
            @Override
            public void onSuccessful(VersionBean bean) {
                String versionName = bean.getData().getVersion().replace(".", "");
                int versionCode = 0;
                if (!TextUtils.isEmpty(versionName)) {
                    versionCode = Integer.parseInt(versionName);
                }
                if (versionCode > VersionUtil.packageCode(mActivity)) {
                    if (bean.getData().getForce_update() == 1) {
                        dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                        dialogBuild.setMessage("发现新版本，请升级");
                        dialogBuild.setPositiveVersionButton("去升级", v -> {
                            goToMarket(mActivity, getPackageName());
                        });
                        dialogBuild.setCancelable(false);
                        dialogBuild.show();
                        dialogBuild.setNegativeButtonGONE();
                    } else {
                        dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                        dialogBuild.setMessage("发现新版本，请升级");
                        dialogBuild.setPositiveVersionButton("去升级", v -> {
                            dialogBuild.dismiss();
                            dialogBuild = null;
                            goToMarket(mActivity, getPackageName());
                        });
                        dialogBuild.setNegativeButton("取消", v -> {
                            dialogBuild.dismiss();
                            dialogBuild = null;
                        });
                        dialogBuild.setCancelable(false);
                        dialogBuild.show();
                    }
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * @param context
     * @param packageName
     */
    public static void goToMarket(Context context, String packageName) {
        try {
            Uri uri = Uri.parse("market://details?id=" + packageName);
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(context, "您的手机没有安装Android应用市场", Toast.LENGTH_SHORT).show();
        }
    }




    @RequiresApi(api = Build.VERSION_CODES.M)
    public boolean isIgnoringBatteryOptimizations() {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
        }
        return isIgnoring;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void requestIgnoreBatteryOptimizations() {
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Subscribe
    public void ReLoginEvent(ReLoginEvent event) {
        if (dialogBuild == null) {
            SPManager.getInstance().logOffRemove();
            Intent intent = new Intent(MyApplication.getApplication(), MainActivity.class);
            intent.putExtra(MainActivity.MAIN_TAB, MainActivity.fragmentTag_home);
            startActivity(intent);
            dialogBuild = new CommonNoTitleDialog.Builder(this);
            dialogBuild.setMessage("登录已过期，是否重新登录");
            dialogBuild.setPositiveButton("登录", v -> {
                dialogBuild.dismiss();
                startActivity(new Intent(mActivity, LoginActivity.class));
                dialogBuild = null;
            });
            dialogBuild.setNegativeButton("否", v -> {
                dialogBuild.dismiss();
                dialogBuild = null;
            });
            dialogBuild.setCancelable(false);
            dialogBuild.show();
        }
    }

    /**
     * 获取权限
     */
    public void getPermissions() {
        permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//
                Manifest.permission.READ_EXTERNAL_STORAGE, //
                Manifest.permission.ACCESS_FINE_LOCATION, //
                Manifest.permission.READ_PHONE_STATE};

        if (PermissionsManager.checkPermissions(permissions)) {
            getCurrentLocationCity();//获得当前定位城市
            return;
        }
        permissionsManager = new PermissionsManager(this);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                getCurrentLocationCity();//获得当前定位城市
            } else {
                permissionsManager.showDialog();
                getCurrentLocationCity();
            }
        });

        permissionsManager.requestPermissionsEach(permissions);

    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            getCurrentLocationCity();//获得当前定位城市
        }
    }

    public void getCurrentLocationCity() {
        aMapManager = new AMapManager();
        aMapManager.getOnceLocation(aMapLocation -> {
            aMapManager.onDestroy();
            if (aMapLocation.getErrorCode() == 0) {//获得了定位
                requestUpLngLat(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            } else {
                    ToastUtil.showShort("定位失败，检查定位权限");
            }
        });
    }

    public void requestUpLngLat(double latitude, double longitude) {
        String lat = NumberFormatUtils.formatDecimal6(latitude + "");
        String lng = NumberFormatUtils.formatDecimal6(longitude + "");
        new MineModelImpl().requestUpLngLat(lat, lng, lng + "|" + lat, "", new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String mTab = intent.getStringExtra(MAIN_TAB);

        if (fragmentTag_home.equals(mTab)) {
            llHomePage.performClick();
        } else if (fragmentTag_mine.equals(mTab)) {
            llMine.performClick();
        }
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        if (homePageFragment == null && fragment instanceof HomePageFragment)
            homePageFragment = (HomePageFragment) fragment;
        if (mineFragment == null && fragment instanceof MineFragment)
            mineFragment = (MineFragment) fragment;
    }

    // 当fragment已被实例化，相当于发生过切换，就隐藏起来
    public void hideFragments(FragmentTransaction ft) {
        if (homePageFragment != null)
            ft.hide(homePageFragment);
        if (mineFragment != null)
            ft.hide(mineFragment);
    }

    /**
     * fragment 的显示和隐藏
     */
    private void handlerFragmentShowHide(String tag) {
        FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
        hideFragments(ft2);
        switch (tag) {
            case fragmentTag_home:
                if (homePageFragment != null)
                    ft2.show(homePageFragment);
                else {
                    homePageFragment = new HomePageFragment();
                    ft2.add(R.id.fragment_container, homePageFragment);
                }
                break;
            case fragmentTag_mine:
                if (mineFragment != null)
                    ft2.show(mineFragment);
                else {
                    mineFragment = new MineFragment();
                    ft2.add(R.id.fragment_container, mineFragment);
                }
                break;
        }
        ft2.commitAllowingStateLoss();
        getSupportFragmentManager().executePendingTransactions();
    }


    public void checkHomeButton(int position) {

        switch (position) {
            case 0:
                llHomePage.performClick();
                break;
            case 1:
                llMine.performClick();
                break;
        }

    }

    /**
     * 设置默认图标
     */
    private void setAllIconNormal() {

        int textColor = getResources().getColor(R.color.text_color_4);
        tvHome.setTextColor(textColor);
        tvMine.setTextColor(textColor);

        ivHomeIcon.setImageResource(R.mipmap.ic_home_unchecked);
        ivMineIcon.setImageResource(R.mipmap.ic_me_uncheck);

    }

    @OnClick({R.id.ll_home_page, R.id.ll_mine, R.id.ll_scan})
    public void onViewClicked(View view) {
        int color_checked = getResources().getColor(R.color.theme_color);
        switch (view.getId()) {
            case R.id.ll_home_page:
                setAllIconNormal();
                tvHome.setTextColor(color_checked);
                ivHomeIcon.setImageResource(R.mipmap.ic_home_checked);
                handlerFragmentShowHide(fragmentTag_home);
                break;
            case R.id.ll_mine:
                setAllIconNormal();
                tvMine.setTextColor(color_checked);
                ivMineIcon.setImageResource(R.mipmap.ic_me_checked);
                handlerFragmentShowHide(fragmentTag_mine);
                break;
            case R.id.ll_scan:
                showActivity(ScanCodeActivity.class);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
    }

}
